package ca.uwo.android.directoryservice;

import java.util.ArrayList;

import org.json.JSONArray;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.SearchRecentSuggestions;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;
import ca.uwo.android.BaseListMenuActivity;
import ca.uwo.android.R;
import ca.uwo.android.sslconnection.WesternHttpClient;

public class DirectoryService extends BaseListMenuActivity {
	private ImageButton search;
	private ToggleButton faculty;
	private ToggleButton student;
	private DirectoryConnectionHandler searchHandler;
	private DirectorySearchListViewAdapter adapter;
	private AlertDialog alertDialog;
	private WesternHttpClient httpClient;
	
	private ArrayList<DirectorySearchData> dataList;
	private final Exception[] lastException = new Exception[1];

	final Handler updateAdapter = new Handler(){     
		public void handleMessage(Message msg) {
			if(dataList != null) {
				adapter.setData(dataList);
				adapter.notifyDataSetChanged();
			}
		}            
	};

	final Handler searchFailed = new Handler() {
		public void handleMessage (Message msg) {
			if(lastException[0] != null) {
				alert("Search Failed ", lastException[0].getMessage());
				lastException[0] = null;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.directory_service);
		setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); 
		handleIntent(getIntent());
		lastException[0] = null;
		
		TextView title = (TextView)findViewById(R.id.moduleName);
		title.setText("Western Directory");
		title.setSingleLine();
		title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
		
		search = (ImageButton)findViewById(R.id.searchButton);
		faculty = (ToggleButton)findViewById(R.id.dsSelectFaculty);
		student = (ToggleButton)findViewById(R.id.dsSelectStudent);

		dataList = new ArrayList<DirectorySearchData>();

		adapter = new DirectorySearchListViewAdapter(this);
		setListAdapter(adapter);

		httpClient = new WesternHttpClient(this);
		searchHandler = new DirectoryConnectionHandler(httpClient);



		search.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				onSearchClicked();
			}
		});

		faculty.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				((ToggleButton)v).setChecked(true);

				if(student.isChecked()) {
					if(dataList != null) {
						dataList = JSONDataParser.getFaculty();
						adapter.setData(dataList);
						adapter.notifyDataSetChanged();
					}
				}

				student.setChecked(false);
			}
		});

		student.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				((ToggleButton)v).setChecked(true);

				if(faculty.isChecked()) {
					if(dataList != null) {
						dataList = JSONDataParser.getStudents();
						adapter.setData(dataList);
						adapter.notifyDataSetChanged();
					}
				}

				faculty.setChecked(false);
			}
		});
		
	

	}
	
	/**
	 * Handle configuration changes ourselves.
	 * Implementing this method and adding android:configChanges="keyboardHidden|orientation"
	 * to the manifest for this activity means that the onCreate method will not be
	 * called every time a user rotates their phone.
	 */
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	protected void onSearchClicked() {
		onSearchRequested();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		handleIntent(intent);
	}

	private void handleIntent(Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			searchDir(query);
			SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
					SuggestionProvider.AUTHORITY, SuggestionProvider.MODE);
			suggestions.saveRecentQuery(query, null);
		}

	}

	protected void searchDir(final String query) {
		
		final ProgressDialog loadDialog = ProgressDialog.show(DirectoryService.this, "", "Searching...", true);

		Thread searchThread = new Thread() {

			public void run() {
				String str = query.trim();		
				if(str == null)
					return;

				boolean isFaculty = faculty.isChecked();
				String firstname = null;
				String lastname = null;
				String query = null;
				String searchString = null;
				
				String[] names = null;
				
				//split the first name/last name on whitepace chars
				names = str.split("\\s+");
				
				if(names.length < 1){
					alert("Invalid search argument", "The search argument must contain a value.");
				}
				else if(names.length == 1){
					firstname = names[0];
					lastname = "";
				}
				if(names.length > 1){
					firstname = names[0];
					lastname = "";
					for(int i = 1; i < names.length; i++){
						lastname += names[i];	
					}
				}

				if(lastname.length() > 0)
					searchString = "*" + lastname + "*,";
				else
					searchString = "*,";

				if(firstname.length() > 0)
					searchString = searchString + "*" + firstname + "*";
				else
					searchString = searchString + "*";		

				query = isFaculty ? getString(R.string.faculty_search) : getString(R.string.student_search);
				query = query + searchString;

				try {
					JSONArray result = searchHandler.DSearch(query);
					dataList = isFaculty ? JSONDataParser.parseFaculty(result) : JSONDataParser.parseStudent(result);
					
					updateAdapter.sendEmptyMessage(0);
				}
				catch(Exception e) {
					//error Handling;
					lastException[0] = e;
					searchFailed.sendEmptyMessage(0);
				}
				finally {
					loadDialog.dismiss();
				}
			}
		};

		searchThread.start();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		DirectorySearchData data = dataList.get(position);
		showDetail(data);

		super.onListItemClick(l, v, position, id);
	}

	private void alert(String title, String msg) {
		alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle(title);
		alertDialog.setMessage(msg);
		alertDialog.setButton("OK",new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog, int which) {
				return;
			} }); 
		alertDialog.show();	
	}
	
	private void showDetail(DirectorySearchData data) {
	
			Intent showContact = new Intent(DirectoryService.this,
					ca.uwo.android.directoryservice.ContactActivity.class);

			// pass the information required to populate fields in summary
			// screen
			showContact.putExtra("DATA", data);
			
			startActivity(showContact); // display the summary screen to the

	}
}